package com.yupi.springbootinit.biMq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.InvalidEchartsUtil;
import com.yupi.springbootinit.webSocket.WebSocketServer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;
    @Resource
    private AiManager aiManager;

    @Resource
    private WebSocketServer webSocketServer;


    @SneakyThrows
    @RabbitListener(queues = {Biconstant.QUEUE_NAME},ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long delivery_tag){
        if (StringUtils.isBlank(message)){
            channel.basicNack(delivery_tag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null){
            channel.basicAck(delivery_tag,false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"图标为空");
        }
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(delivery_tag,false,false);
            handleChartUpdataError(chart.getId(), "更新图标执行中状态失败");
            return;
        }
        String userInput = buildUserInput(chart);
        //调用AI
        String answer = aiManager.doChat(CommonConstant.BI_MODEL_ID, userInput);
        String[] split = answer.split("【【【【【");
        if (split.length < 3) {
            channel.basicNack(delivery_tag,false,false);
            handleChartUpdataError(chart.getId(), "ai生成错误");
            return;
        }
        String genChart = split[1].trim();//trim去掉多余的空格换行
        boolean isValid = InvalidEchartsUtil.checkEchartsTest(genChart);
        String genResult = split[2].trim();
        isValid = false;
        if (!isValid) {
            try {
                genChart = aiManager.doChatWithRetry(genChart);
            } catch (Exception e) {
                // 如果重试过程中出现异常，返回错误信息
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, e + "，AI生成错误");
            }
        }
        isValid = InvalidEchartsUtil.checkEchartsTest(genChart);
        //重试后仍然出错
        if (!isValid){
            Chart invalidChart = new Chart();
            invalidChart.setId(chartId);
            invalidChart.setStatus("failed");
            boolean invalidSaveResult = chartService.updateById(invalidChart);
            if (!invalidSaveResult){
                handleChartUpdataError(chart.getId(), "且AI生成的图标代码还不符合规范");
            }else {
                webSocketServer.sendToAllClient("AI好像生成的有误，请刷新并重试");
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI生成的图标代码不符合规范");
            }
        }

        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus("succeed");
        boolean b2 = chartService.updateById(updateChartResult);
        if (!b2) {
            channel.basicNack(delivery_tag,false,false);
            handleChartUpdataError(chart.getId(), "更新图标成功状态失败");
        }

        log.info("receiveMessage message = {}", message);
        webSocketServer.sendToAllClient("图表生成好啦，快去看看吧！");
        channel.basicAck(delivery_tag,false);
    }

    private String buildUserInput(Chart chart){
        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析目标:").append("\n");
        String userGoal = chart.getGoal();
        if (StringUtils.isNotBlank(chart.getChartType())){
            userGoal = ".请使用"+chart.getChartType();
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据:").append("\n");
        //压缩后的数据
        String csvData = chart.getChartData();
        userInput.append(csvData).append("\n");
        return userInput.toString();
    }

    private void handleChartUpdataError(long charId,String s){
        Chart updateChartResult = new Chart();
        updateChartResult.setId(charId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage("execMessage");
        boolean b3 = chartService.updateById(updateChartResult);
        if (!b3){
            log.error("更新图标失败状态失败"+charId+","+s);
        }
//        throw new BusinessException(ErrorCode.OPERATION_ERROR,charId+s);
    }
}
